//
// Created by 田建昆 on 2020/12/21.
//

#include "list.h"

void list_init(list_t *list, void (*destroy)(void *data))
{
    list->size = 0;
    list->head = list->tail = NULL;
    if (destroy != NULL) {
        list->destroy = destroy;
    }else {
        list->destroy = free;
    }

}
void list_destroy(list_t *list)
{
    void *data;
    while (list_len(list) > 0) {
        if (list_rem_next(list, NULL, &data) == 0 && list->destroy != NULL) {
            list->destroy(data);
        }
    }
    memset(list, 0, sizeof(list_t));
}

int list_ins_next(list_t *list, list_node_t *node, void *data)
{
    list_node_t *newnode;
    newnode = malloc(sizeof(list_node_t));
    newnode->data = data;

    if (node != NULL) {
        if (node->next == NULL) {
            list->tail = newnode;
        }
        newnode->next = node->next;
        node->next = newnode;
    } else {
        if (list_len(list) == 0) {
            list->tail = newnode;
        }
        newnode->next = list->head;
        list->head = newnode;
    }
    list->size++;
    return 0;
}

int list_rem_next(list_t *list, list_node_t *node, void **data)
{
    list_node_t *oldnode;

    if (list_len(list) == 0) return -1;

    if (node == NULL) {
        *data = list->head->data;
        oldnode = list->head;
        list->head = list->head->next;
        if (list_len(list) == 1) {
            list->tail = NULL;
        }
    } else {
        if (list_is_tail(node)) return -1;
        *data = node->next->data;
        oldnode = node->next;
        node->next = node->next->next;
        if (node->next == NULL) {
            list->tail = node;
        }
    }
    if (oldnode != NULL) {
        free(oldnode);

    }

    list->size--;
    return 0;
}